package com.zenithmind.classroom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenithmind.common.result.PageResult;
import com.zenithmind.classroom.mapper.CourseMapper;
import com.zenithmind.classroom.pojo.dto.CourseCreateDTO;
import com.zenithmind.classroom.pojo.dto.CourseQueryDTO;
import com.zenithmind.classroom.pojo.dto.CourseUpdateDTO;
import com.zenithmind.classroom.pojo.domain.Course;
import com.zenithmind.classroom.pojo.vo.CourseDetailVO;
import com.zenithmind.classroom.pojo.vo.CourseStatisticsVO;
import com.zenithmind.classroom.pojo.vo.CourseVO;
import com.zenithmind.classroom.service.CourseService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 课程服务实现类
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CourseVO createCourse(CourseCreateDTO createDTO) {
        log.info("创建课程: {}", createDTO.getTitle());
        
        Course course = new Course();
        BeanUtils.copyProperties(createDTO, course);
        course.setStatus(createDTO.getPublishNow() != null && createDTO.getPublishNow() ? 1 : 0);
        course.setCreateTime(LocalDateTime.now());
        course.setUpdateTime(LocalDateTime.now());
        
        // 设置默认值
        if (course.getStudentCount() == null) {
            course.setStudentCount(0L);
        }
        if (course.getCompletedCount() == null) {
            course.setCompletedCount(0L);
        }
        if (course.getRating() == null) {
            course.setRating(0.0);
        }
        if (course.getReviewCount() == null) {
            course.setReviewCount(0L);
        }
        
        save(course);
        
        return convertToVO(course);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateCourse(String id, CourseUpdateDTO updateDTO) {
        log.info("更新课程: {}", id);
        
        Course course = getById(id);
        if (course == null) {
            throw new RuntimeException("课程不存在");
        }
        
        BeanUtils.copyProperties(updateDTO, course);
        course.setUpdateTime(LocalDateTime.now());
        
        return updateById(course);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteCourse(String id) {
        log.info("删除课程: {}", id);
        
        Course course = getById(id);
        if (course == null) {
            throw new RuntimeException("课程不存在");
        }
        
        // 软删除
        course.setIsDeleted(1);
        course.setUpdateTime(LocalDateTime.now());
        
        return updateById(course);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean publishCourse(String id) {
        log.info("发布课程: {}", id);
        
        Course course = getById(id);
        if (course == null) {
            throw new RuntimeException("课程不存在");
        }
        
        course.setStatus(1); // 已发布
        course.setPublishTime(LocalDateTime.now());
        course.setUpdateTime(LocalDateTime.now());
        
        return updateById(course);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean unpublishCourse(String id) {
        log.info("下架课程: {}", id);
        
        Course course = getById(id);
        if (course == null) {
            throw new RuntimeException("课程不存在");
        }
        
        course.setStatus(2); // 已下架
        course.setUpdateTime(LocalDateTime.now());
        
        return updateById(course);
    }

    @Override
    public PageResult<CourseVO> getCoursePage(CourseQueryDTO queryDTO) {
        log.info("分页查询课程: {}", queryDTO);
        
        LambdaQueryWrapper<Course> wrapper = new LambdaQueryWrapper<>();
        
        // 构建查询条件
        if (StringUtils.hasText(queryDTO.getKeyword())) {
            wrapper.and(w -> w.like(Course::getTitle, queryDTO.getKeyword())
                    .or().like(Course::getDescription, queryDTO.getKeyword()));
        }
        
        if (StringUtils.hasText(queryDTO.getCategoryId())) {
            wrapper.eq(Course::getCategoryId, queryDTO.getCategoryId());
        }
        
        if (StringUtils.hasText(queryDTO.getInstructorId())) {
            wrapper.eq(Course::getInstructorId, queryDTO.getInstructorId());
        }
        
        if (queryDTO.getStatus() != null) {
            wrapper.eq(Course::getStatus, queryDTO.getStatus());
        }
        
        if (queryDTO.getDifficulty() != null) {
            wrapper.eq(Course::getDifficulty, queryDTO.getDifficulty());
        }
        
        if (queryDTO.getType() != null) {
            wrapper.eq(Course::getType, queryDTO.getType());
        }
        
        if (queryDTO.getIsFree() != null) {
            wrapper.eq(Course::getIsFree, queryDTO.getIsFree());
        }
        
        if (queryDTO.getIsRecommend() != null) {
            wrapper.eq(Course::getIsRecommend, queryDTO.getIsRecommend());
        }
        
        if (queryDTO.getIsHot() != null) {
            wrapper.eq(Course::getIsHot, queryDTO.getIsHot());
        }
        
        if (queryDTO.getIsNew() != null) {
            wrapper.eq(Course::getIsNew, queryDTO.getIsNew());
        }
        
        if (queryDTO.getMinPrice() != null) {
            wrapper.ge(Course::getPrice, queryDTO.getMinPrice());
        }
        
        if (queryDTO.getMaxPrice() != null) {
            wrapper.le(Course::getPrice, queryDTO.getMaxPrice());
        }
        
        if (queryDTO.getCreateStartTime() != null) {
            wrapper.ge(Course::getCreateTime, queryDTO.getCreateStartTime());
        }
        
        if (queryDTO.getCreateEndTime() != null) {
            wrapper.le(Course::getCreateTime, queryDTO.getCreateEndTime());
        }
        
        // 排除已删除的记录
        if (!Boolean.TRUE.equals(queryDTO.getIncludeDeleted())) {
            wrapper.eq(Course::getIsDeleted, 0);
        }
        
        // 排序
        if (StringUtils.hasText(queryDTO.getSortField())) {
            if ("desc".equalsIgnoreCase(queryDTO.getSortOrder())) {
                wrapper.orderByDesc(Course::getCreateTime); // 默认按创建时间降序
            } else {
                wrapper.orderByAsc(Course::getCreateTime);
            }
        } else {
            wrapper.orderByDesc(Course::getCreateTime);
        }
        
        // 分页查询
        Page<Course> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
        IPage<Course> pageResult = page(page, wrapper);
        
        // 转换为VO
        List<CourseVO> courseVOs = pageResult.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        return PageResult.of(courseVOs, pageResult.getTotal());
    }

    @Override
    public CourseDetailVO getCourseDetail(String id, String userId) {
        log.info("获取课程详情: courseId={}, userId={}", id, userId);
        
        Course course = getById(id);
        if (course == null) {
            throw new RuntimeException("课程不存在");
        }
        
        CourseDetailVO detailVO = new CourseDetailVO();
        BeanUtils.copyProperties(course, detailVO);
        
        // TODO: 补充详细信息，如章节列表、用户学习进度等
        
        return detailVO;
    }

    @Override
    public List<CourseVO> getRecommendCourses(String userId, Integer limit) {
        log.info("获取推荐课程: userId={}, limit={}", userId, limit);
        
        LambdaQueryWrapper<Course> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Course::getStatus, 1) // 已发布
                .eq(Course::getIsDeleted, 0) // 未删除
                .eq(Course::getIsRecommend, 1) // 推荐课程
                .orderByDesc(Course::getStudentCount) // 按学习人数降序
                .last("LIMIT " + limit);
        
        List<Course> courses = list(wrapper);
        return courses.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    @Override
    public List<CourseVO> getHotCourses(Integer limit) {
        log.info("获取热门课程: limit={}", limit);
        
        LambdaQueryWrapper<Course> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Course::getStatus, 1) // 已发布
                .eq(Course::getIsDeleted, 0) // 未删除
                .eq(Course::getIsHot, 1) // 热门课程
                .orderByDesc(Course::getStudentCount) // 按学习人数降序
                .last("LIMIT " + limit);
        
        List<Course> courses = list(wrapper);
        return courses.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    @Override
    public List<CourseVO> getLatestCourses(Integer limit) {
        log.info("获取最新课程: limit={}", limit);
        
        LambdaQueryWrapper<Course> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Course::getStatus, 1) // 已发布
                .eq(Course::getIsDeleted, 0) // 未删除
                .orderByDesc(Course::getPublishTime) // 按发布时间降序
                .last("LIMIT " + limit);
        
        List<Course> courses = list(wrapper);
        return courses.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    // TODO: 实现其他方法...

    /**
     * 转换为VO
     */
    private CourseVO convertToVO(Course course) {
        CourseVO vo = new CourseVO();
        BeanUtils.copyProperties(course, vo);
        
        // 设置状态名称
        vo.setStatusName(getStatusName(course.getStatus()));
        vo.setDifficultyName(getDifficultyName(course.getDifficulty()));
        vo.setTypeName(getTypeName(course.getType()));
        
        // 计算完成率
        if (course.getStudentCount() != null && course.getStudentCount() > 0) {
            vo.setCompletionRate(course.getCompletedCount().doubleValue() / course.getStudentCount().doubleValue() * 100);
        } else {
            vo.setCompletionRate(0.0);
        }
        
        // TODO: 补充其他字段转换
        
        return vo;
    }

    private String getStatusName(Integer status) {
        if (status == null) return "未知";
        switch (status) {
            case 0: return "草稿";
            case 1: return "已发布";
            case 2: return "已下架";
            case 3: return "审核中";
            default: return "未知";
        }
    }

    private String getDifficultyName(Integer difficulty) {
        if (difficulty == null) return "未知";
        switch (difficulty) {
            case 1: return "入门";
            case 2: return "初级";
            case 3: return "中级";
            case 4: return "高级";
            case 5: return "专家";
            default: return "未知";
        }
    }

    private String getTypeName(Integer type) {
        if (type == null) return "未知";
        switch (type) {
            case 1: return "录播课程";
            case 2: return "直播课程";
            case 3: return "混合课程";
            default: return "未知";
        }
    }

    // 其他未实现的方法需要根据具体业务逻辑补充
    @Override
    public List<CourseVO> searchCourses(String keyword, Integer limit) {
        // TODO: 实现搜索逻辑
        return null;
    }

    @Override
    public List<CourseVO> getUserCourses(String userId, Integer status, Integer limit) {
        // TODO: 实现获取用户课程逻辑
        return null;
    }

    @Override
    public List<CourseVO> getInstructorCourses(String instructorId, Integer limit) {
        // TODO: 实现获取讲师课程逻辑
        return null;
    }

    @Override
    public List<CourseVO> getCategoryCourses(String categoryId, Integer limit) {
        // TODO: 实现获取分类课程逻辑
        return null;
    }

    @Override
    public List<CourseVO> getRelatedCourses(String courseId, Integer limit) {
        // TODO: 实现获取相关课程逻辑
        return null;
    }

    @Override
    public Boolean favoriteCourse(String courseId, String userId) {
        // TODO: 实现收藏课程逻辑
        return null;
    }

    @Override
    public Boolean unfavoriteCourse(String courseId, String userId) {
        // TODO: 实现取消收藏逻辑
        return null;
    }

    @Override
    public List<CourseVO> getFavoriteCourses(String userId, Integer limit) {
        // TODO: 实现获取收藏课程逻辑
        return null;
    }

    @Override
    public Boolean rateCourse(String courseId, String userId, Integer rating, String comment) {
        // TODO: 实现评价课程逻辑
        return null;
    }

    @Override
    public Boolean updateCourseStatistics(String courseId, Long studentCount, Long completedCount) {
        // TODO: 实现更新统计逻辑
        return null;
    }

    @Override
    public CourseStatisticsVO getCourseStatistics(String courseId) {
        // TODO: 实现获取统计逻辑
        return null;
    }

    @Override
    public Integer batchImportCourses(List<CourseCreateDTO> courses) {
        // TODO: 实现批量导入逻辑
        return null;
    }

    @Override
    public List<CourseVO> exportCourses(List<String> courseIds) {
        // TODO: 实现导出逻辑
        return null;
    }

    @Override
    public CourseVO copyCourse(String courseId, String title) {
        // TODO: 实现复制课程逻辑
        return null;
    }

    @Override
    public Boolean reviewCourse(String courseId, Boolean approved, String comment) {
        // TODO: 实现审核课程逻辑
        return null;
    }
}
